import 'package:web_socket_channel/io.dart';
import 'dart:convert';
class MySocket {
  static MySocket instance = new MySocket();

  // 链接的wss地址
  IOWebSocketChannel wss;
  String name;

  MySocket({IOWebSocketChannel socket, String name1}){
    wss = socket;
    name = name1;
  }
  Map listenList = {};

  static MySocket getInstance() {
    return instance;
  }

  emits(String name, Map data){
    Map msgData = {
      'name': name,
      'data': data
    };
    instance.wss.sink.add(json.encode(msgData));
  }

  lisenMsg (dynamic data) {
    Map msgData = json.decode(data);
    if (instance.listenList[msgData['event']] != null) {
      instance.listenList[msgData['event']].forEach((item){
        item(msgData['data']);
      });
    }
  }

  onmsg (String name, Function fun) {
    if (instance.listenList[name] == null) {
      instance.listenList[name] = [];
    }
    instance.listenList[name]..add(fun);
  }

  myWss () => instance.wss;
  get iname => instance.name;
  getname () => iname;

}